package user

import (
	"coarse_score_cal_flow/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
	"time"
)

var users = []model.User{
	{ID: 1, Age: 20, Name: "Alpha"},
	{ID: 2, Age: 25, Name: "Beta"},
	{ID: 3, Age: 30, Name: "Charlie"},
}

func MatchByJson(c *gin.Context) {
	var user model.User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "User created", "user": user})
}

func MatchByForm(c *gin.Context) {
	var user model.User
	if err := c.Bind(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "User created", "user": user})
}

func GetByNameAndAgeForm(c *gin.Context) {
	name := c.DefaultPostForm("name", "Alpha")
	fmt.Println(c.PostForm("age"))
	age, _ := strconv.ParseInt(c.PostForm("age"), 10, 32)
	id, _ := strconv.Atoi(c.Query("id"))

	for _, user := range users {
		if user.Age == int32(age) && user.Name == name && user.ID == int32(id) {
			c.JSON(http.StatusOK, gin.H{
				"name": user.Name,
				"age":  user.Age,
				"id":   user.ID,
			})
			return
		}
	}
}

func AsyncCal(c *gin.Context) {
	copyContext := c.Copy()
	go func() {
		time.Sleep(10 * time.Second)
		log.Println("async execute: " + copyContext.Request.RequestURI)
	}()
}
